package com.sunflower.sunflower.controller;


import com.sunflower.sunflower.entity.WechatMessageEntity;
import com.sunflower.sunflower.util.MessgaeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

//@RequestMapping("/web")
@RestController
public class IndexController {

    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Value("${wechet.token}")
    private String TOKEN;


    public void doPost() {
    }


    @RequestMapping(value = "/signature", method = {RequestMethod.GET})
    public String checkToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 接收到数据
//        ServletInputStream inputStream = request.getInputStream();
//        byte[] bytes = new byte[1024];
//        int len;
//        StringBuilder sb = new StringBuilder();
//        while ((len = inputStream.read(bytes))!= -1){
//            sb.append(new String(bytes,0,len));
//        }
//        logger.info(sb.toString());


        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        String[] strings = new String[]{TOKEN, timestamp, nonce};
        StringBuilder builder = new StringBuilder();
        Arrays.sort(strings);
        for (int i = 0; i < strings.length; i++) {
            builder.append(strings[i]);
        }
        String res = sha1(builder.toString());
        logger.info("加密后：" + res);
        if (signature.equalsIgnoreCase(res)) {
            logger.info("验证成功！");
            return echostr;
        }
        logger.info("验证失败");
        return "";
    }

    @RequestMapping(value = "/signature", method = RequestMethod.POST)
    public void getWechatMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        logger.info("接收到消息");
        String str = null;
        Map<String, String> map = MessgaeUtils.xmlToMap(request);

        String ToUserName = map.get("ToUserName");
        String FromUserName = map.get("FromUserName");
        String CreateTime = map.get("CreateTime");
        String MsgType = map.get("MsgType");
        String Content = map.get("Content");
        String MsgId = map.get("MsgId");
        WechatMessageEntity message = new WechatMessageEntity();
        //这里只处理文本消息
        if (MsgType.equalsIgnoreCase("text")) {

            message.setFromUserName(FromUserName);
            message.setToUserName(ToUserName);
            message.setContent(Content);
            message.setMsgId(MsgId);
            message.setMsgType("text");
            message.setCreateTime(new Date().getTime());
            str = MessgaeUtils.objectToXml(message);
        }
        logger.info(str);

        String responseXml = "<xml>" +
                "<ToUserName><![CDATA["+message.getFromUserName()+"]]></ToUserName>" +
                "<FromUserName><![CDATA["+message.getToUserName()+"]]></FromUserName>" +
                "<CreateTime>"+System.currentTimeMillis()/1000+"</CreateTime>" +
                "<MsgType><![CDATA[text]]></MsgType>" +
                "<Content><![CDATA["+"测试消息"+"]]></Content>" +
                "</xml>";
        System.out.println(responseXml);
        PrintWriter writer =  response.getWriter();
        writer.print(responseXml);
        writer.flush();
        writer.close();
    }


    private String sha1(String str) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            byte[] bytes = digest.digest(str.getBytes());
            return toHex(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    private String toHex(byte[] bytes) {
        String str = "";
        for (byte b : bytes) {
            char[] chars = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
            char[] temp = new char[2];
            temp[0] = chars[(b >>> 4) & 0x0F];
            temp[1] = chars[b & 0x0F];

            str += new String(temp);
        }
        return str;
    }

}
